package firstping.controller;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import firstping.data.QnAPersistenceManager;
import firstping.model.Customer;
import firstping.model.Domain;
import firstping.string.Utils;

@SuppressWarnings("serial")
public class CronpayServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		String invoice = req.getParameter("invoice");
		
		if(invoice != null)
		{
			PersistenceManager psm = QnAPersistenceManager.get().getPersistenceManager();
			Query query3 = psm.newQuery(Customer.class);
			query3.setFilter("invoice=='"+invoice+"'");
			@SuppressWarnings("unchecked")
			List<Customer> user = (List<Customer>) query3.execute();
			if(user.size() > 0)
			{
				long month = 6;
				switch(Integer.parseInt(user.get(0).getMoney()))
				{
					case 14:
						month = 6;
						break;
					case 24:
						month = 12;
						break;
					case 35:
						month = 18;
						break;
					case 50:
						month = 24;
						break;	
				}
				
				long endDate = new Date().getTime();
				
				if(endDate < user.get(0).getEndDate().getTime())
				{
					endDate = user.get(0).getEndDate().getTime();
				}
				
				Date up = new Date(endDate+month*30*24*60*60*1000);
				user.get(0).setEndDate(up);
				user.get(0).setType(month+" Months");
				
				psm=JDOHelper.getPersistenceManager(user.get(0));
    			psm.currentTransaction().begin();
    			psm.makePersistent(user.get(0));
    			psm.currentTransaction().commit();
    			
    			Query query = psm.newQuery(Domain.class);
    			query.setFilter("email=='"+user.get(0).getEmail()+"'");
    			@SuppressWarnings("unchecked")
				List<Domain> updates = (List<Domain>) query.execute();
    			if(updates.size() > 0)
    			{
    				for (int i = 0; i < updates.size(); i++) {
						updates.get(0).setEndDate(up);
						updates.get(0).setActive("1");
						psm=JDOHelper.getPersistenceManager(updates.get(0));
		    			psm.currentTransaction().begin();
		    			psm.makePersistent(updates.get(0));
		    			psm.currentTransaction().commit();
					}
    			}
    			
    			Properties props = new Properties();
    	        Session sessions = Session.getDefaultInstance(props, null);
    	        String email = user.get(0).getEmail();
    			String emails = "Firstping.com support";
    			
    			Format formatter = new SimpleDateFormat("MM/dd/yy");
				String s = formatter.format(up);
				String s1 = formatter.format(new Date(endDate));
    			
    	        String text = "Email : "+email+"<br/><br/>";
    	        text += "Total : $"+user.get(0).getMoney()+"<br/><br/>";
    	        text += "Service package : "+month+" Months"+"<br/><br/><br/>";
    	        text += "Start date : "+s1+"<br/><br/><br/>";
    	        text += "Exp date : "+s+"<br/><br/><br/>";
    	        text += "If you have any question, please contact us via email : admin@firstping.com";
    	        String msgBody = text;

    	        try {
    	            Message msg = new MimeMessage(sessions);
    	            msg.setFrom(new InternetAddress("admin@firstping.com",emails));
    	            msg.addRecipient(Message.RecipientType.TO,
    	                             new InternetAddress(email,email));
    	            msg.setSubject("Payment successful");
    	            msg.setContent(msgBody, "text/html");
    	            Transport.send(msg);
    	           
    	        } catch (AddressException e1) {
    	            // ...
    	        } catch (MessagingException e1) {
    	            // ...
    	        }
			}
		}
	}
}
